package com.primb.bench.project.init.presenter;

import android.content.Context;
import android.os.Handler;

import com.primb.bench.common.override.HttpSubscriber;
import com.primb.bench.project.init.contract.LoginContract;
import com.primb.bench.project.init.entity.LoginEntity;
import com.primb.bench.project.init.model.LoginModelImpl;
import com.primb.netlibs.exception.ApiException;

import rx.Subscription;
import rx.subscriptions.CompositeSubscription;


/**
 * Created by Administrator on 2017/04/13
 */

public class LoginPresenterImpl implements LoginContract.Presenter {
    private LoginContract.View mView;
    private LoginModelImpl loginModel;
    private CompositeSubscription subscription;
    private Context context;

    public LoginPresenterImpl(Context context,LoginContract.View view) {
        this.mView = view;
        this.context = context;
        loginModel = new LoginModelImpl();
        subscription = new CompositeSubscription();
    }

    @Override
    public void start() {
        if (!mView.isEmpty(mView.getAccountStr(), mView.getPwdStr())) {
            mView.showLoading();
            Subscription subscribe = loginModel.login(mView.getAccountStr(), mView.getPwdStr()).subscribe(new HttpSubscriber<LoginEntity>(context) {

                @Override
                public void onError(ApiException e) {
                    mView.showError(e.getMessage());
                    mView.hideLoading();
                }

                @Override
                public void onCompleted() {
                    mView.hideLoading();
                }

                @Override
                public void onNext(LoginEntity entity) {
                    mView.intentToMain(entity);
                }
            });
            subscription.add(subscribe);
        } else {
            mView.showError("用户名或者密码为空，请完善后重试");
        }
    }

    @Override
    public void onRecycle() {
        subscription.clear();
    }
}